package com.example.administrator.bluetoothdemo01;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.bluetoothdemo01.util.Constant;
import com.example.administrator.bluetoothdemo01.util.LogUtils;
import com.example.administrator.bluetoothdemo01.view.DeviceAdapter;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import connect.AcceptThread;
import connect.ConnectThread;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.is_isVisiable_blue_tooth)
    Button mIsIsVisiableBlueTooth;
    @Bind(R.id.is_support_blue_tooth)
    Button mIsSupportBlueTooth;
    @Bind(R.id.is_open_blue_tooth)
    Button mIsOpenBlueTooth;
    @Bind(R.id.is_turnOb_blue_tooth)
    Button mIsTurnObBlueTooth;
    @Bind(R.id.is_turnOff_blue_tooth)
    Button mIsTurnOffBlueTooth;
    @Bind(R.id.lv)
    ListView mLv;
    @Bind(R.id.is_findDevice_blue_tooth)
    Button mIsFindDeviceBlueTooth;
    @Bind(R.id.is_findBouondDevice_blue_tooth)
    Button mIsFindBouondDeviceBlueTooth;
    @Bind(R.id.is_serverWaitAccept_blue_tooth)
    Button mIsServerWaitAcceptBlueTooth;
    @Bind(R.id.is_serverStopAccept_blue_tooth)
    Button mIsServerStopAcceptBlueTooth;
    @Bind(R.id.is_ClientStopConnect_blue_tooth)
    Button mIsClientStopConnectBlueTooth;
    @Bind(R.id.sendhello)
    Button mSendhello;
    @Bind(R.id.sayhi)
    Button mSayhi;
    @Bind(R.id.server_to_client)
    Button mServerToClient;

    private BluetoothController mBluetoothController = new BluetoothController();
    List<BluetoothDevice> mDeviceList = new ArrayList<>();
    private DeviceAdapter mDeviceAdapter;
    private List<BluetoothDevice> mBoundedDeviceList;
    private AcceptThread mAcceptThread;
    private ConnectThread mConnectThread;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.MSG_START_LISTENING:
                    Toast.makeText(MainActivity.this, "开始监听", Toast.LENGTH_SHORT).show();
                    break;
                case Constant.MSG_END_LISTENING:
                    Toast.makeText(MainActivity.this, "结束监听", Toast.LENGTH_SHORT).show();
                    break;
                case Constant.MSG_GOT_A_CLINET:
                    Toast.makeText(MainActivity.this, "有(另外一个)客户端连接", Toast.LENGTH_SHORT).show();
                    break;
                case Constant.MSG_CONNECTED_TO_SERVER:
                    Toast.makeText(MainActivity.this, "连接到服务器", Toast.LENGTH_SHORT).show();
                    break;
                case Constant.MSG_GOT_DATA:
                    Toast.makeText(MainActivity.this, "获取数据 msg=" + (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case Constant.MSG_DATA_ERROR:
                    Toast.makeText(MainActivity.this, "(连接好了)数据传输失败", Toast.LENGTH_SHORT).show();
                    break;
                case Constant.MSG_ERROR:
                    Toast.makeText(MainActivity.this, "传输失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    /*蓝牙真实状态*/
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int intExtra = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
            switch (intExtra) {
                case BluetoothAdapter.STATE_OFF:
                    LogUtils.logd("onReceive 蓝牙状态 STATE_OFF");
                    break;
                case BluetoothAdapter.STATE_ON:
                    LogUtils.logd("onReceive 蓝牙状态 STATE_ON");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    LogUtils.logd("onReceive 蓝牙状态 TURNING_ON");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    LogUtils.logd("onReceive 蓝牙状态 TURNING_OFF");
                    break;
                default:
                    LogUtils.logd("没这种状态");
                    break;
            }

        }
    };
    private ScanDeviceBroadCaseReceiver mScanDeviceBroad;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        //初始化listview
        mDeviceAdapter = new DeviceAdapter(mDeviceList, this);
        mLv.setAdapter(mDeviceAdapter);

        //注册广播(蓝牙状态))
        IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver, intentFilter);

        //注册广播（扫描状态）
        mScanDeviceBroad = new ScanDeviceBroadCaseReceiver();
        registerScanDeviceBroadCaseReceiver(mScanDeviceBroad);


    }

    private void registerScanDeviceBroadCaseReceiver(ScanDeviceBroadCaseReceiver broadCaseReceiver) {
        IntentFilter filter = new IntentFilter();
        //开始查找
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        //结束查找
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        //查找设备
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        //设备扫描模式改变
        filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        //绑定状态
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);

        registerReceiver(broadCaseReceiver, filter);
    }

    @OnClick({R.id.is_support_blue_tooth, R.id.is_open_blue_tooth, R.id.is_turnOb_blue_tooth, R.id.is_turnOff_blue_tooth,
            R.id.is_isVisiable_blue_tooth, R.id.is_findDevice_blue_tooth, R.id.is_findBouondDevice_blue_tooth,
            R.id.is_serverWaitAccept_blue_tooth, R.id.is_serverStopAccept_blue_tooth, R.id.is_ClientStopConnect_blue_tooth,
            R.id.sendhello, R.id.sayhi, R.id.server_to_client})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.is_support_blue_tooth:
                boolean supportBlueTooth = mBluetoothController.isSupportBlueTooth();
                LogUtils.logd("supportBlueTooth = " + supportBlueTooth);
                break;
            case R.id.is_open_blue_tooth:
                boolean blueToothStatues = mBluetoothController.getBlueToothStatues();
                LogUtils.logd("blueToothStatues = " + blueToothStatues);
                break;
            case R.id.is_turnOb_blue_tooth:
                mBluetoothController.turnOnBluetooth(this, RESULT_OK);
                break;
            case R.id.is_turnOff_blue_tooth:
                boolean b = mBluetoothController.turnOffBluetooth();
                LogUtils.logd("turnOffBluetooth = " + b);
                break;
            case R.id.is_isVisiable_blue_tooth:
                mBluetoothController.enableVisibly(this); // 打开蓝牙可见性
                break;
            case R.id.is_findDevice_blue_tooth: // 查找设备
                /*6.0*/
                checkVersion();
                break;
            case R.id.is_findBouondDevice_blue_tooth: // 查找已绑定的设备
                Toast.makeText(this, "查找已绑定的设备", Toast.LENGTH_SHORT).show();
                mBoundedDeviceList = mBluetoothController.getBondeDeviceList();
                mDeviceAdapter.refreshListView(mBoundedDeviceList);
                mLv.setOnItemClickListener(mbindedDeviceList);
                break;
            case R.id.is_serverWaitAccept_blue_tooth: // 服务器 启动监听（等待客户端连接）
                if (mAcceptThread != null) {
                    mAcceptThread.cancel();
                }
                mAcceptThread = new AcceptThread(mHandler, mBluetoothController.getAdapter());
                mAcceptThread.start();
                break;
            case R.id.is_serverStopAccept_blue_tooth:
                if (mAcceptThread != null) {
                    mAcceptThread.cancel();
                }
                break;
            case R.id.is_ClientStopConnect_blue_tooth:
                if (mConnectThread != null) {
                    mConnectThread.cancel();
                }
                break;
            case R.id.sendhello:
                clientSay("Hello!");
                break;
            case R.id.sayhi:
                clientSay("Hi!");
                break;
            case R.id.server_to_client:
                ServerSay("Server Say hi !");
                break;
        }
    }


    /*6.0 位置权限*/
    private void checkVersion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0以上
            int checkPermission = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
            if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);//后面的1为请求码
                return;
            }else{
                ScanDevices(); //搜权过
            }
        }else {
            ScanDevices();  //低于 6.0 不需要运行时权限
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //如果同时申请多个权限，可以for循环遍历
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //写入你需要权限才能使用的方法
            ScanDevices();
        } else {
            // 没有获取 到权限，从新请求，或者关闭app
            Toast.makeText(this,"需要获得LOCATION权限",Toast.LENGTH_SHORT).show();
        }
    }
    private void ScanDevices() {
        Toast.makeText(this, "查找设备", Toast.LENGTH_SHORT).show();
        mDeviceAdapter.refreshListView(null);
        mBluetoothController.findDevice();   // -----》 结果右广播 完成显示
        mLv.setOnItemClickListener(mBindDeviceClik);
    }

    private void clientSay(String s) {
        try {
            mConnectThread.sendData(s.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void ServerSay(String s) {
        try {
            mAcceptThread.sendData(s.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    public class ScanDeviceBroadCaseReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                //数据初始化列表
                mDeviceList.clear();
                mDeviceAdapter.refreshListView(mDeviceList);
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //停止查找设备
                Toast.makeText(context, "停止查找设备", Toast.LENGTH_SHORT).show();
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //查找到设备 添加显示列表
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mDeviceList.add(device);
                mDeviceAdapter.refreshListView(mDeviceList);
            }

        }

    }


    // （已绑定的）设备列表 item 点击事件回调
    AdapterView.OnItemClickListener mbindedDeviceList = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(MainActivity.this, " （已绑定的）设备列表 item 点击事件回调", Toast.LENGTH_SHORT).show();
            BluetoothDevice device = mBoundedDeviceList.get(position);
            mConnectThread = new ConnectThread(device, mBluetoothController.getAdapter(), mHandler);
            mConnectThread.start();
        }
    };


    // (查找到的)设备列表 item 点击事件回调
    AdapterView.OnItemClickListener mBindDeviceClik = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            BluetoothDevice device = mDeviceList.get(position);
            device.createBond();   //绑定蓝牙设备
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_OK) {
            LogUtils.logd("蓝牙打开成功");
        } else {
            LogUtils.logd("蓝牙打开失败");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver); // 蓝牙 status
        unregisterReceiver(mScanDeviceBroad); // scan status
    }


}
